﻿using System;
using System.ComponentModel;
using System.Linq;
using ProjectEuler.Linq;

namespace ProjectEuler.Problems
{
    [EulerProblem(30, 443839)]
    [Description("Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.")]
    internal sealed class Problem030 : EulerProblem
    {
        public override Object Solve()
        {
            return (from n in MaxPossibleValue().To(10)
                    where n == n.DecimalDigits().Select(d => Terms[d]).Sum()
                    select n).Sum();
        }

        private static Int32 MaxPossibleValue()
        {
            var i = 1;
            var sum = Terms[9];

            while (i < Math.Log10(sum))
            {
                i++;
                sum = i * Terms[9];
            }
            
            return sum;
        }

        private static readonly Int32[] Terms = new[]
        {
            /* 0**5 */ 0,
            /* 1**5 */ 1,
            /* 2**5 */ 32,
            /* 3**5 */ 243,
            /* 4**5 */ 1024,
            /* 5**5 */ 3125,
            /* 6**5 */ 7776,
            /* 7**5 */ 16807,
            /* 8**5 */ 32768,
            /* 9**5 */ 59049,
        };
    }
}
